﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using NPOI.HSSF.UserModel;
using System.Web;
using System.IO;
using SPMS.Common;
using NPOI.SS.UserModel;
using SPMS.Web.Models;
using SPMS.Data;
using SPMS.Web.Models;
using SPMS.Web.Mvc;
using System.Transactions;

namespace SPMS.Web.Controllers
{
    [AuthorizeEx]
    public class BlacklistController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [JsonHandleError]
        public ActionResult Import()
        {
            if (this.Request.Files == null || this.Request.Files.Count == 0)
                return this.JsonEx(false, "没有上传文件！"); // no data.

            var loadFile = this.Request.Files[0];
            var buffer = new byte[loadFile.InputStream.Length];
            int count = 0;

            using (var stream = new MemoryStream())
            {
                var loadFileName = loadFile.FileName.ToLower();
                if (!loadFileName.EndsWith(".xls") && !loadFileName.EndsWith(".xlsx"))
                    return this.JsonEx(false, "上传文件类型错误！"); // invalid file type.

                //read the memory.
                int read;
                while ((read = loadFile.InputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, read);
                }
                stream.Position = 0;

                IWorkbook workbook;
                if (loadFileName.EndsWith(".xls"))
                    workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(stream);
                else
                    workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(stream);

                var importWorksheet = workbook.GetSheetAt(0);
                int rowindex = 2; //start row index.

                var row = importWorksheet.GetRow(rowindex);
                if (row == null)
                    return this.JsonEx(false, "空 Excel 数据文件！"); //no import data.

                using (var context = new AccountFileManagementEntities())
                {
                    var accountID = row.GetCell(0).StringCellValue;
                    var organizationName = row.GetCell(1).StringCellValue;

                    while (row != null)
                    {
                        Guid parsedAccoutID;
                        if (Guid.TryParse(accountID, out parsedAccoutID) && !string.IsNullOrEmpty(organizationName))
                        {
                            var entity = new Blacklist
                            {
                                BlackListID = Guid.NewGuid(),
                                AccountID = parsedAccoutID,
                                OrganizationName = organizationName,
                                BusinessAddress = row.GetCell(2).StringCellValue,
                                Businesslicense_SN = row.GetCell(3).StringCellValue,
                                OrganizationCodeCertificate_SN = row.GetCell(4).StringCellValue,
                                TaxRegistrationCertificate_SN = row.GetCell(5).StringCellValue,
                                AccountOpeningLicense_SN = row.GetCell(6).StringCellValue,
                                ArtificialPersonID = row.GetCell(7).StringCellValue,
                                ArtificialPersonName = row.GetCell(8).StringCellValue,
                                CreditAgenciesCodeCard = row.GetCell(9).StringCellValue
                            };

                            context.Blacklists.Add(entity);
                            count++;
                        }

                        rowindex++;
                        row = importWorksheet.GetRow(rowindex);

                        if (row == null)
                            break;

                        accountID = row.GetCell(0).StringCellValue;
                        organizationName = row.GetCell(1).StringCellValue;
                    }

                    if (count > 0)
                    {
                        using (var transaction = new TransactionScope())
                        {
                            context.SaveChanges();
                            transaction.Complete();
                        }
                    }
                }
            }


            return this.JsonEx(true, new { count });
        }

        [HttpGet]
        [JsonHandleError]
        public JsonResult List(JsonPagingQueryModel queryModel)
        {
            //创建上下文
            using (var context = new AccountFileManagementEntities())
            {
                //用于保存总记录数
                int totalRecord = 0;

                //查询数据
                var query = from item in context.Blacklists.QueryData<Blacklist>(queryModel, out totalRecord)
                            select new
                            {
                                item.BlackListID,
                                item.AccountID,
                                item.OrganizationName,
                                item.BusinessAddress,
                                item.Businesslicense_SN,
                                item.OrganizationCodeCertificate_SN,
                                item.TaxRegistrationCertificate_SN,
                                item.AccountOpeningLicense_SN,
                                item.ArtificialPersonID,
                                item.ArtificialPersonName,
                                item.CreditAgenciesCodeCard
                            };

                //获得数据
                var data = query.ToArray();

                return this.JsonEx(true, data, totalRecord);
            }
        }
    }
}
